import 'package:flutter/material.dart';

class ImageTapWidget extends StatefulWidget {
  final Widget child;
  final Function() onTap;

  const ImageTapWidget({Key? key, required this.child, required this.onTap})
      : super(key: key);

  @override
  ImageTapWidgetState createState() {
    return new ImageTapWidgetState();
  }
}

class ImageTapWidgetState extends State<ImageTapWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _ctl;

  @override
  void initState() {
    super.initState();
    _ctl =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
  }

  @override
  void dispose() {
    _ctl.stop();
    _ctl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: AnimatedBuilder(
        animation: _ctl,
        builder: (BuildContext context, Widget? child) {
          return LayoutBuilder(builder: (ctx, BoxConstraints constraints) {
            return Container(
              foregroundDecoration: BoxDecoration(
                  color: Colors.lightBlue.withOpacity(0.3 * _ctl.value),
                  borderRadius:
                      BorderRadius.circular(constraints.maxHeight / 2)),
              child: widget.child,
            );
          });
        },
      ),
      onTap: widget.onTap,
      onTapDown: (d) => _ctl.forward(),
      onTapUp: (d) => prepareToIdle(),
      onTapCancel: () => prepareToIdle(),
    );
  }

  void prepareToIdle() {
    AnimationStatusListener? listener;
    listener = (AnimationStatus statue) {
      if (statue == AnimationStatus.completed) {
        _ctl.removeStatusListener(listener!);
        toStart();
      }
    };
    _ctl.addStatusListener(listener);
    if (!_ctl.isAnimating) {
      _ctl.removeStatusListener(listener);
      toStart();
    }
  }

  void toStart() {
    _ctl.stop();
    _ctl.reverse();
  }
}
